package com.boang.lock;

/*
  @author: 13813
  @date: 2024/11/26 13:57
*/
public class TicketDemoSys03 implements Runnable {
    private int num = 20;
    private Object lock = new Object();
    /*
       同步代码块
       synchronized (任意对象) {
           有可能出现线程安全问题的代码
       }
     */

    @Override
    public void run() {
        while (true) {
            //获取当前线程
            synchronized (lock) { //t1
                if (num > 0) {
                    try {
                        Thread.sleep(300);//t0
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + num--); //t0 0 t1 -1 t2 -2
                }
            }
        }
    }
}
